<?php

namespace app\api\controller\study;

use app\common\controller\Api;
use think\Db;


class Study extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 视频列表
     * @ApiMethod (GET)
     * @path api/study/study/lookVideo
     */
    public function lookVideo()
    {
        
        $userId = $this->auth->id;
        $where = [];
        $page = $this->request->param('page',1);
        $video = db('video')
            ->where($where)
            ->order('createtime DESC')
            ->paginate(10, false, ['page' => $page]);
            
        if (!empty($video)) {
            $video = $video->toArray();
            $video['data'] = addWebSiteUrl($video['data'],['image']);
            foreach ($video['data'] AS $key => $value) {
                
                if ($value['pv'] >= 10000) {
                    // 浏览量过万，以w结尾
                    $video['data'][$key]['pv'] = floor($value['pv'] / 10000) . 'w+';
                }
                if (empty($value['pv'])) {
                    $video['data'][$key]['pv'] = 0;
                }
                $video['data'][$key]['createtime'] = date('m-d H:i',strtotime($video['data'][$key]['createtime']));
            }
        }
        $this->success('操作成功',$video);
    }

    /**
     * 直播列表
     * @ApiMethod (GET)
     * @path api/study/study/lookVideoLive
     */
    public function lookVideoLive()
    {
        $userId = $this->auth->id;
        $where = [];
        $today = date('Y-m-d H:i:s');
        $page = $this->request->param('page',1);
        $video = db('video_live')
            ->where($where)
            ->order('createtime DESC')
            ->paginate(10, false, ['page' => $page]);
        if (!empty($video)) {
            $video = $video->toArray();
            $video['data'] = addWebSiteUrl($video['data'],['image']);

            foreach ($video['data'] AS $key => $value) {
                $video['data'][$key]['status'] = '未开始';
                if ($today >=$value['start_time'] && $today <= $value['end_time']) {
                    $video['data'][$key]['status'] = '直播中';
                } elseif ($today < $value['start_time']) {
                    $video['data'][$key]['status'] = '未开始';
                } elseif ($today > $value['end_time']) {
                    $video['data'][$key]['status'] = '已结束';
                }
            }
        }
        $this->success('操作成功',$video);
    }

    /**
     * 提交观看时长
     * @ApiMethod (GET)
     * @path api/study/study/lookVideoTime
     */
    public function lookVideoTime()
    {
        $userId = $this->auth->id;
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $videoId = $this->request->param('video_id',0);
        $longTime = $this->request->param('long_time',0);
        $type = $this->request->param('type',1);
        $today = date('Y-m-d H:i:s');
        $todayD = date('Y-m-d');
        Db::startTrans();
        try{
            //观看记录
            $videoLogId = db('user_video_log')->insertGetId([
                'user_id'=>$userId,
                'store_id'=>$storeId,
                'video_id'=>$videoId,
                'type'=>$type,
                'long_time'=>$longTime,
                'addtime'=>$today
            ]);
            
            db('video')->where('id',$videoId)->setInc('pv',1);
            
            $expDay = db('integral_score_rule')->where('type',5)->value('day');//过期时长
            $rule = db('integral_score_rule')->where('type',$type)->find();
            $sendScore = $rule['score'];
            if ($longTime >= $rule['long_time']) {
                //赠送积分
                db('user')->where('id',$userId)->lock(true)->find();
                db('user')->where('id',$userId)->setInc('integral',$sendScore);
                $integral = db('user')->where('id',$userId)->value('integral');
                $expInt = strtotime($todayD)+$expDay*86400+86400;
                db('integral_change_log')->insert([
                    'user_id'=>$userId,
                    'store_id'=>$storeId,
                    'scene'=>$type,
                    'score'=>$sendScore,
                    'total_score'=>$integral,
                    'residue_score'=>$sendScore,
                    'type'=>2,
                    'long_time'=>$longTime,
                    'video_log_id'=>$videoLogId,
                    'exptime'=>date('Y-m-d H:i:s',$expInt),
                    'addtime'=>date('Y-m-d H:i:s',time())
                ]);
            } else {
                Db::commit();
                $this->error('未达到赠送积分观看时长');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success('积分+'.$rule['score']);
    }
}
